package com.alcatel_lucent.osp.action;

import com.alcatel_lucent.osp.model.Attachment;
import com.alcatel_lucent.osp.service.AttachmentService;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: guoshunw
 * Date: 13-8-28
 * Time: 下午2:20
 */

@Result(type = "stream", params = {"contentType", "${mimeType}", "inputName", "inStream", "contentDisposition", "attachment;filename=\"${filename}\""})
public class DownloadAttachmentAction extends BaseAction implements
        ServletContextAware {

    private InputStream inStream;
    private String mimeType;
    private String filename;

    private ServletContext context;

    private Long id;

    private AttachmentService attachmentService;

    @Autowired
    public void setAttachmentService(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getFilename() {
        return filename;
    }

    public String getMimeType() {
        return mimeType;
    }

    public InputStream getInStream() {
        return inStream;
    }

    @Override
    public String execute() throws Exception {
        log.info("id={}, filename={}", id, filename);
        Attachment attachment = attachmentService.findAttachmentById(id);
        inStream = attachmentService.getAttachmentInputStream(id);
        if (null == filename) filename = attachment.getName();
        mimeType = context.getMimeType(filename);
        if (null == mimeType) mimeType = "application/octet-stream";

        return SUCCESS;
    }

    @Override
    public void setServletContext(ServletContext context) {
        this.context = context;
    }
}
